/*
 * @lc app=leetcode.cn id=105 lang=javascript
 *
 * [105] 从前序与中序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */
// 迭代版
var buildTree = function(preorder, inorder) {
  const stack = []
  const root = new TreeNode(preorder[0])
  stack.push(root)
  let inorderIndex = 0
  for (let i = 1; i < preorder.length; i++) {
    const preorderItem = preorder[i]
    let node = stack[stack.length - 1]
    // 将当前分支的左节点都加入堆栈
    if (node.val !== inorder[inorderIndex]) {
      node.left = new TreeNode(preorderItem)
      stack.push(node.left)
    } else {
      // 左节点不做处理
      while (stack.length && stack[stack.length - 1].val === inorder[inorderIndex]) {
        // 当前处理的node,如果下一个节点值和中序遍历对应位置的值不同，那么就是当前处理的节点的右节点
        node = stack.pop()
        inorderIndex++
      }
      // 处理右节点
      node.right = new TreeNode(preorderItem)
      stack.push(node.right)
    }
  }
  return root
};
// @lc code=end

